package org.hertsig.entities;

import lombok.AllArgsConstructor;

import com.google.common.annotations.VisibleForTesting;

@AllArgsConstructor
public class PowerAndToughness {
	public static final PowerOrToughnessValue VARIABLE = new PowerOrToughnessValue(0) {
		@Override
		public String toString() {
			return "*";
		}};
	
	private static class PowerOrToughnessValue {
		private final int value;
		
		private PowerOrToughnessValue() {
			value = -1;
		}
		
		private PowerOrToughnessValue(int value) {
			this.value = value;
		}
		
		@Override
		public String toString() {
			return String.valueOf(value);
		}
	}
	
	private static class VariablePowerOrToughnessValue extends PowerOrToughnessValue {
		private VariablePowerOrToughnessValue(int value) {
			super(value);
		}
		
		@Override
		public String toString() {
			return super.toString() + "+*";
		}
	}
	
	public static PowerAndToughness parse(String type) {
		String[] split = type.split("/");
		if (split.length != 2) {
			throw new IllegalArgumentException("Invalid power/toughness format: " + type);
		}
		
		PowerOrToughnessValue power = parseValue(split[0]);
		PowerOrToughnessValue toughness = parseValue(split[1]);
		return new PowerAndToughness(power, toughness);
	}
	
	@VisibleForTesting static PowerOrToughnessValue parseValue(String string) {
		if ("*".equals(string)) {
			return VARIABLE;
		}
		if (string.endsWith("+*")) {
			return new VariablePowerOrToughnessValue(Integer.parseInt(string.substring(0, string.length() - 2)));
		}
		if (string.endsWith("-*")) {
			return new VariablePowerOrToughnessValue(-Integer.parseInt(string.substring(0, string.length() - 2)));
		}
		return new PowerOrToughnessValue(Integer.parseInt(string));
	}
	
	private final PowerOrToughnessValue power;
	private final PowerOrToughnessValue toughness;
	
	@Override
	public String toString() {
		return power + "/" + toughness;
	}
	
	public int getPower() {
		return power.value;
	}
	
	public int getToughness() {
		return toughness.value;
	}
}
